#!/usr/bin/env python
#coding:utf-8
import urllib
import re
import sqlite3

def main():
    # Show Information
    print '中国城市天气查询'

    # Get Parameters
    city = raw_input('请输入您要查询天气的城市名字（如北京，广州...):')

    # Request For Web Page
    params = urllib.urlencode({'city':city})
    webpage = urllib.urlopen('http://weather.news.sohu.com/city.php?%s'%params)
    webdata = webpage.read().replace('\n','')

    # Match The Useful Information
    pattern = re.compile('<td class=blu01>([^<]*)<br>([^<]*)<br>([^<]*)')

    db = sqlite3.connect('weather.db')

    db.execute("create table if not exists message(id integer primary key autoincrement,tianqi varchar(128),wendu varchar(128),fengli varchar(128),jianshuilv varchar(128))")
    cur = db.cursor()
    x = 0
    for weather in pattern.findall(webdata):
        if x == 0:
            riqi = '今天'
        elif x == 1:
            riqi = '明天'
        else:
            riqi = '后天'

        for i in range(4):
            print weather.strip()

        tianqi = weather[0]
        wendu = weather[1]
        fengli = weather[2]
        jiangshuilv = weather[3]

        #print tianqi,wendu,fengli,jiangshuilv

        sss = "INSERT INTO message VALUES('%s', '%s', '%s', '%s', '%s')" % \
              (riqi, tianqi, wendu, fengli, jiangshuilv)

        #print sss
        cur.execute(sss)
        db.commit()
        x += 1
        cur.close()
        db.close()

if __name__ == '__main__':
    main()
